<?php
/**
 * Created by PhpStorm.
 * User: ship
 * Date: 2025/1/2
 * Time: 16:49
 */

namespace ShipSun\LaravelRequestResponseJm;

use Illuminate\Http\Request;

/**
 * Class BaseMiddleware
 * @package ShipSun\LaravelRequestResponseJm
 */
abstract class BaseMiddleware
{
    /**
     * @var RequestResponseEncrypter
     */
    protected $encrypter;
    public static $enable = false;
    public static $jm_key = '123456';
    /**
     * @var array
     */
    public static $close_path = ['/login'];

    /**
     * ResponseMiddleware constructor.
     * @param RequestResponseEncrypter $requestResponseEncrypter
     */
    public function __construct(RequestResponseEncrypter $requestResponseEncrypter)
    {
        $this->encrypter = $requestResponseEncrypter;
    }

    /**
     * @param Request $request
     * @return bool
     */
    protected function isJm(Request $request)
    {
        if ($this->isEnable($request) &&
            $this->allowMethod($request) &&
            $this->allowPath($request->getPathInfo())
        ) {
            return true;
        }
        return false;
    }

    /**
     * @param $path
     * @return bool
     */
    protected function allowPath($path)
    {
        $path = '/' . trim($path, '/');
        foreach (static::$close_path as $searchPath) {
            if (strpos($path, $searchPath) === 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param Request $request
     * @return bool
     */
    protected function isEnable(Request $request)
    {
        $key = $request->headers->get('jm_key');
        if (static::$enable || $key == static::$jm_key) {
            return true;
        }
        return false;
    }

    abstract protected function allowMethod(Request $request);
}